# —————————————————————————————————————————————————————————————————— #
import torch
import torch.nn as nn
import torch.nn.functional as F
import sys
sys.path.append("./")
sys.path.append("../")
import mymodel.utils as utils
torch.manual_seed(1337)

# —————————————————————————————————————————————————————————————————— #
'''超参数'''
device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")
batch_size = 4
block_size = 8
max_iter = 5000
eval_iter = 200
lr = 2e-3
eval_interval = 500
n_embd = 32
n_heads = 4

# —————————————————————————————————————————————————————————————————— #
'''读入数据'''
with open("./TRANSFORMER/dataset.txt", "r", encoding="utf-8") as f:
    text = f.read()
text_len = len(text)
chars = sorted(list(set(text))) # 提取所有不重复字符并放在一个列表中排序
vocab_size = len(chars)

# —————————————————————————————————————————————————————————————————— #
print(f"----------- {__file__} on device {device} start -----------")

# —————————————————————————————————————————————————————————————————— #
'''解码编码器索引字符相互转化'''
stoi = {ch:idx for idx,ch in enumerate(chars)}
itos = chars
encoder = lambda s: [stoi[c] for c in s]
decoder = lambda idxs: "".join([itos[idx] for idx in idxs])

# —————————————————————————————————————————————————————————————————— #
'''把数据分成训练集和验证集'''
data = torch.tensor(encoder(text), dtype=torch.long) # 全文的索引
n_90 = int(text_len*0.9)
train_data = data[:n_90].to(device=device)
val_data = data[n_90:].to(device=device)
# —————————————————————————————————————————————————————————————————— #
'''在评估模式下同时对训练和测试进行损失评估，取几个随机批量的平均值'''
@torch.no_grad
def estimate_loss():
    out = {}
    model.eval()
    for split in ["train", "val"]:
        losses = torch.zeros(eval_iter)
        for k in range(eval_iter):
            X, Y = get_batch(split)
            _, loss = model(X, Y)
            losses[k] = loss.mean()
        out[split] = losses.mean()
    model.train()
    return out

# —————————————————————————————————————————————————————————————————— #
'''获取一批输入输出 y的位置对应x的target'''
def get_batch(mode="train"):
    (data, data_len) = (train_data, n_90) if mode == "train" else (val_data, text_len-n_90)
    idxs = torch.randint(0, data_len-1-block_size, (batch_size,)) # 生成一个起始索引
    x = torch.stack([data[idx:idx+block_size] for idx in idxs]) # 根据索引生成批量数据(batch_size, block_size)
    y = torch.stack([data[idx+1:idx+block_size+1] for idx in idxs]) # x往后偏移一位
    return x, y
# —————————————————————————————————————————————————————————————————— #
'''自注意头'''
class Head(nn.Module):
    def __init__(self, head_size) -> None:
        super().__init__()
        # 所有层的输入肯定是词嵌入的向量维度
        self.key = nn.Linear(n_embd, head_size, bias=False)
        self.quary = nn.Linear(n_embd, head_size, bias=False)
        self.value = nn.Linear(n_embd, head_size, bias=False)
        # 蒙版，但是不用参加训练但必要的参数
        self.register_buffer("tril", torch.tril(torch.ones((block_size, block_size), device=device)))

    def forward(self, x):
        _, T, C = x.shape
        k = self.key(x)
        q = self.quary(x)
        v = self.value(x) # (B, T, Head_size)

        wei = q @ k.transpose(-2, -1) / C**0.5 # 权重的规范化，k的最后两个维度进行了转置
        wei = wei.masked_fill(self.tril[:T, :T]==0, float("-inf")) # 避免未来的字符影响预测
        wei = F.softmax(wei, dim=-1) # （B, T, T）

        out = wei @ v # (B, T, Head_size)
        return out

class MultiHead_Attention(nn.Module):
    def __init__(self, n_heads, head_size) -> None:
        super().__init__()
        self.heads = nn.ModuleList([Head(head_size) for _ in range(n_heads)])

    def forward(self, x):
        return torch.cat([h(x) for h in self.heads], dim=-1)

class Block(nn.Module):
    def __init__(self, n_embd, n_head) -> None:
        super().__init__()
        head_size = n_embd//n_head
        self.heads = MultiHead_Attention(n_head, head_size)
        self.sffd = FeedForward(n_embd)

    def forward(self, x):
        x = self.heads(x)
        x = self.sffd(x)
        return x
# —————————————————————————————————————————————————————————————————— #
'''前反馈层'''
class FeedForward(nn.Module):
    def __init__(self, n_embd) -> None:
        super().__init__()
        self.net = nn.Sequential(
            nn.Linear(n_embd, n_embd),
            nn.ReLU()
        )
    
    def forward(self, x):
        return self.net(x)

# —————————————————————————————————————————————————————————————————— #
class BigramLanuageModel(nn.Module):
    def __init__(self) -> None:
        super().__init__()
        # 词嵌入和位置嵌入
        self.token_embedding_table = nn.Embedding(vocab_size, n_embd)
        self.position_embedding_tabel = nn.Embedding(block_size, n_embd)
        self.blocks = nn.Sequential(
            Block(n_embd, n_heads),
            Block(n_embd, n_heads),
            Block(n_embd, n_heads),
        )
        self.lh_linear = nn.Linear(n_embd, vocab_size)

    def forward(self, batch_x, batch_y=None):
        B, T = batch_x.shape
        token_embd = self.token_embedding_table(batch_x) # （B, T, n_embd）
        position_embd = self.position_embedding_tabel(torch.arange(T, device=device)) # （T, n_embd）
        x = token_embd + position_embd # 广播机制相加（B, T, n_embd）
        x = self.blocks(x) # (B, T, Head_size)
        logits = self.lh_linear(x) #（B, T, vocab_size）

        if batch_y is None:
            loss = None
        else:
            B, T, C  = logits.shape
            loss = F.cross_entropy(logits.view(B*T, C), batch_y.view(B*T))
        return logits, loss
    
    def generater(self, batch_x, max_size):
        # 这里的batch_x 是(batch, 1)因为仅凭一个词汇预测 
        for _ in range(max_size):
            # 这边不用担心越界问题，如果越界只会取有的部分
            logits, _ = self.forward(batch_x[:, -block_size:])
            probs = F.softmax(logits[:, -1], dim=1)
            batch_x_next = torch.multinomial(probs, 1, replacement=True)
            batch_x = torch.cat((batch_x, batch_x_next), dim=1)
        return batch_x

# —————————————————————————————————————————————————————————————————— #
@utils.timer
def train():
    for iters in range(max_iter):
        bx, by = get_batch()
        _, loss = model(bx, by)
        optim.zero_grad(set_to_none=True)
        loss.backward()
        optim.step()
        if iters%eval_interval==0:
            losses = estimate_loss()
            print(f"[step {iters}] {losses}")

# —————————————————————————————————————————————————————————————————— #
'''main'''
model = BigramLanuageModel().to(device)
optim = torch.optim.AdamW(model.parameters(), lr=1e-3)
train()
test_x = torch.zeros((1,1), dtype=torch.long, device=device)
losses = estimate_loss()
print(f"[loss]:{losses}")
print(f"[generate test]:{decoder(model.generater(test_x, eval_iter)[0].tolist())}")
print(f"----------- {__file__} on device {device} end -----------")
# —————————————————————————————————————————————————————————————————— #
